package demo2;

import java.util.Stack;

public class Sort1 {
    //归并排序  非递归
    public static void merge (int[] array, int low, int mid, int high) {
        int[] tmp = new int[high - low + 1];
        int k = 0;
        int s1 = low;
        int e1 = mid;
        int s2 = mid + 1;
        int e2 = high;
        for (; s1 <= e1 && s2 <= e2;) {
            if (array[s1] <= array[s2]) {
                tmp[k++] = array[s1++];
            } else {
                tmp[k++] = array[s2++];
            }
        }
        while (s1 <= e1) {
            tmp[k++] = array[s1++];
        }
        while (s2 <= e2) {
            tmp[k++] = array[s2++];
        }
        for (int i = 0; i < k; i++) {
            array[i + low] = tmp[i];
        }
    }
    public static void mergeSort1 (int[] array) {
        int nums = 1;//每组的数据个数
        while (nums < array.length) {
            //数组每次都要进行遍历,确定要归并的区间
            for (int i = 0; i < array.length; i += nums * 2) {
                int left = i;
                int mid = left + nums - 1;
                //防止越界
                if (mid >= array.length) {
                    mid = array.length - 1;
                }
                int right = mid + nums;
                //防止越界
                if (right >= array.length){
                    right = array.length - 1;
                }
                //下标确定后  进行合并
                merge(array,left,mid,right);
            }
            nums *= 2;
        }
    }


}
